#!/bin/bash

# 上传后端代码到服务器的脚本
echo "======================================"
echo "    上传后端代码到服务器"
echo "======================================"

SERVER_IP="47.237.10.129"
SERVER_USER="root"
BACKEND_DIR="./backend"
REMOTE_DIR="/opt/cumbull"

# 检查本地后端目录
if [ ! -d "$BACKEND_DIR" ]; then
    echo "❌ 本地后端目录不存在: $BACKEND_DIR"
    exit 1
fi

echo "✓ 本地后端目录存在"
echo "准备上传的文件:"
ls -la "$BACKEND_DIR"
echo

# 创建压缩包
echo "创建后端代码压缩包..."
tar -czf backend-upload.tar.gz -C "$BACKEND_DIR" .
echo "✓ 压缩包创建完成: backend-upload.tar.gz"
echo

# 上传到服务器的命令（需要手动执行）
echo "请手动执行以下命令上传代码到服务器:"
echo "======================================"
echo "# 1. 上传压缩包"
echo "scp backend-upload.tar.gz $SERVER_USER@$SERVER_IP:/tmp/"
echo
echo "# 2. 登录服务器"
echo "ssh $SERVER_USER@$SERVER_IP"
echo
echo "# 3. 在服务器上执行以下命令:"
echo "mkdir -p $REMOTE_DIR/backend"
echo "cd $REMOTE_DIR/backend"
echo "tar -xzf /tmp/backend-upload.tar.gz"
echo "ls -la"
echo
echo "# 4. 配置环境变量"
echo "cat > .env.production << 'EOF'"
echo "PORT=8080"
echo "NODE_ENV=production"
echo "DB_HOST=localhost"
echo "DB_USER=cumbull_user"
echo "DB_PASSWORD=CuMrBull2024!"
echo "DB_NAME=cumbull_db"
echo "JWT_SECRET=your-super-secret-jwt-key-2024"
echo "CORS_ORIGIN=*"
echo "EOF"
echo
echo "# 5. 安装依赖并启动"
echo "npm install --production"
echo "pkill -f node"
echo "nohup node start-server.js > /var/log/backend.log 2>&1 &"
echo "sleep 5"
echo "ps aux | grep node | grep -v grep"
echo "netstat -tlnp | grep 8080"
echo "tail -20 /var/log/backend.log"
echo "curl -s http://localhost:8080/health"
echo "======================================"

# 自动创建压缩包
echo "正在创建压缩包..."
if tar -czf backend-upload.tar.gz -C "$BACKEND_DIR" .; then
    echo "✓ 压缩包创建成功: backend-upload.tar.gz"
    echo "文件大小: $(ls -lh backend-upload.tar.gz | awk '{print $5}')"
else
    echo "❌ 压缩包创建失败"
    exit 1
fi

echo
echo "现在请按照上面的命令手动上传和部署后端代码。"
echo "或者直接复制粘贴执行上面的命令。"